package com.qwh.iapstm32;

import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;

public class MainActivity extends SerialPortActivity implements AdapterView.OnItemClickListener {
    public static int rec_state;
    byte[] mBuffer;
    SendingThread mSendingThread;
    public static int yali1, yali2, yali3, wd;
    TextView tvVoltameterValue;
    BatteryView mBatteryView;
    //侧滑菜单的布局
    private DrawerLayout drawerLayout;
    //标题栏
    private Toolbar toolbar;
    private TextView tv_head;
    private String[] items = {"首页", "动态", "设置"};
    private int imgIds[] = {R.mipmap.boat, R.mipmap.elect, R.mipmap.anji};
    //侧滑菜单的内容项
    private ListView listView;
    private MyAdapter adapter;
    //切换的页面
    private Fragment1 f1;
    private Fragment2 f2;
    private Fragment3 f3;

    private ReciveOKListener reciveOKListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvVoltameterValue = (TextView) findViewById(R.id.tv_voltameter_value);
        mBatteryView = (BatteryView) findViewById(R.id.battery_view);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");//设置标题
        tv_head = (TextView) findViewById(R.id.tv_head);
        setSupportActionBar(toolbar);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

//        setDrawerLeftEdgeSize(this,drawerLayout,0.2f);
        listView = (ListView) findViewById(R.id.left_drawer);
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        adapter.setSelectedItem(0);//默认选中第一个item

        f1 = new Fragment1();

        mContent = f1;//默认显示fragment1
        tv_head.setText(items[0]);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.content_frame, f1);
        ft.commit();

        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        drawerToggle.syncState();//将左上角的图标和侧滑监听进行联动 达到动画效果显示
        drawerLayout.addDrawerListener(drawerToggle);//设置侧滑菜单的监听

    }

    class SendingThread extends Thread {

        @Override
        public void run() {
            // while (!isInterrupted()) {

            try {
                if (mOutputStream != null) {
                    mOutputStream.write(mBuffer);
                } else {
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }


            // }
        }

    }

    /**
     * 修改显示的内容 不会重新加载
     **/
    private Fragment mContent;

    public void switchContent(Fragment to) {
        if (mContent != to) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(mContent).add(R.id.content_frame, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(mContent).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        switch (position) {

            case 0:
                tv_head.setText(items[position]);
                if (f1 == null) {
                    f1 = new Fragment1();
                }
                switchContent(f1);
                adapter.setSelectedItem(0);
                break;
            case 1:
                tv_head.setText(items[position]);
                if (f2 == null) {
                    f2 = new Fragment2();
                }
                switchContent(f2);
                adapter.setSelectedItem(1);
                break;
            case 2:
                tv_head.setText(items[position]);
                if (f3 == null) {
                    f3 = new Fragment3();
                }
                switchContent(f3);
                adapter.setSelectedItem(2);
                break;
        }
        drawerLayout.closeDrawers();//自动关闭侧滑菜单
        adapter.notifyDataSetChanged();
    }

    private class MyAdapter extends BaseAdapter {

        private int selestedItemPos = -1;

        @Override
        public int getCount() {
            return items.length;
        }

        @Override
        public Object getItem(int position) {
            return items[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private void setSelectedItem(int positon) {
            this.selestedItemPos = positon;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, parent, false);
                holder = new ViewHolder();
                holder.tv = (TextView) convertView.findViewById(R.id.id_tv);
                holder.icon = (ImageView) convertView.findViewById(R.id.id_icon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv.setText(items[position]);
            holder.icon.setImageResource(imgIds[position]);
            //选中设置字体为高亮显示
            if (selestedItemPos == position) {
                holder.tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
            } else {
                holder.tv.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.hqblack));
            }
            return convertView;
        }

        class ViewHolder {
            TextView tv;
            ImageView icon;
        }
    }


    private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            // 找到 ViewDragHelper 并设置 Accessible 为true
            Field leftDraggerField =//如果你想让右侧菜单也是全屏，只要将对应的 “mLeftDragger” 改为 “mRightDragger”
                    drawerLayout.getClass().getDeclaredField("mLeftDragger");//Right
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);

            // 找到 edgeSizeField 并设置 Accessible 为true
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);

            // 设置新的边缘大小
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x *
                    displayWidthPercentage)));
        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            Log.d(this.getLocalClassName(), e.toString());
        }
    }

    @Override
    protected void onDataReceived(byte[] buffer, int size) {
        if ((buffer[0] == 0x5A) && (buffer[1] == (byte) 0xA5) && (buffer[2] == size - 3)) {
//				 Log.d("qwh", String.valueOf(buffer[0]) + "," + String.valueOf(buffer[1]));
            switch (buffer[3]) {
                case (byte) 0xF0:
                    rec_state = 0xF0;
                    yali1 = (buffer[4] & 0xFF) * 256 + (buffer[5] & 0xFF);
                    yali2 = (buffer[6] & 0xFF) * 256 + (buffer[7] & 0xFF);
                    yali3 = (buffer[8] & 0xFF) * 256 + (buffer[9] & 0xFF);
                    wd = (buffer[10] & 0xFF) * 256 + (buffer[11] & 0xFF);
//                    if(reciveOKListener!=null)
//                    {
//                       reciveOKListener.onReciveOKListener(wd);
//                    }
//				Log.d("qwh", String.valueOf(buffer[5])+" "+String.valueOf(buffer[6])+" "+String.valueOf(buffer[7])+" "+String.valueOf(buffer[8]));

                    //           if(f1 !=null) f1.update();
                    break;
                case (byte) 0xF1:
                    rec_state = 0xF1;
                    break;
                case (byte) 0xF2:
                    rec_state = 0xF2;
                    break;
                case (byte) 0xF3:
                    rec_state = 0xF3;
                    break;
                default:
                    break;
            }
        }
    }

    public interface ReciveOKListener {
        public void onReciveOKListener(int position);
    }

    public void setReciveOKListener(ReciveOKListener reciveOKListener) {
        this.reciveOKListener = reciveOKListener;
    }

    public void sendonce() {

        if (mSerialPort != null) {
            mSendingThread = new SendingThread();
            mSendingThread.start();

        }
    }

}
